import { ImportOutlined, PlusOutlined, TagOutlined, DownOutlined } from '@ant-design/icons';
import { Button, Divider, Dropdown, Menu, message, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { connect, history } from 'umi';
import ProTable from '@ant-design/pro-table';
import { queryLesson, removeLesson, batchRemoveLesson } from './service';
import { HasPermission } from '@/components/AuthComponent/HasPermission';
import db from '@/utils/localstorage';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async selectedRows => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    let result = await batchRemoveLesson({
      ids: selectedRows.map(row => row.id),
    });
    hide();
    if (result.code == 0) {
      message.success('删除成功，即将刷新');
      return true;
    } else {
      message.success(result.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 支持会员卡
 * @param {*} record 
 */
const goToEditFromCard = async record => {
  history.push(`/lesson/list/update/${record.id}?from=card`);
}

/**
 * 跳转详情
 * @param {*} record 
 */
const goDetail = async record => {
  history.replace(`/lesson/list/detail/${record.id}`);
}

const List = props => {
  const { dispatch, coachOptions, courseType, shopList, courseList, coachList } = props
  const actionRef = useRef();
  const [total, setTotal] = React.useState(0)
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cubeLesson/fetchCoach',
        payload: {
          empType: 2,
        },
      })
      dispatch({
        type: 'cubeLesson/selectAllCourse',
        payload: {
          classType: '1'
        },
      })
    }
  }, []);
  const [columns, setColumns] = React.useState([
    {
      title: '课程',
      dataIndex: 'courseId',
      hideInTable: true,
      renderFormItem: () => <Select placeholder="请选择" style={{ width: '100%' }}
        showSearch
        filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
      >
        {
          courseList && courseList.map((item, index) => <Select.Option value={item.id} key={index}>{item.courseName}</Select.Option>)
        }
      </Select>
    },
    {
      title: '课程',
      dataIndex: 'courseName',
      hideInSearch: true,
    },
    {
      title: '教练',
      dataIndex: 'coach',
      render: (_, record) => record.user ? <a onClick={() => go2UserDetail(record.user)}>{record.user.name}</a> : "",
      renderFormItem: () => <Select placeholder="请选择" style={{ width: '100%' }}
        showSearch
        filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
      >
        {
          coachList && coachList.map((item, index) => <Select.Option value={item.userId} key={index}>{item.name}</Select.Option>)
        }
      </Select>
    },
    {
      title: '课程类型',
      dataIndex: 'type',
      render:(text,record)=>{
       if(db.get("dictTypeList") && db.get("dictTypeList")["course_type"]){
        let courseType = db.get("dictTypeList")["course_type"].find(item=>item.value === text);
        if(courseType){
          return courseType?.label;
        }
       }
      },
      renderFormItem: () => <Select placeholder="请选择" style={{ width: '100%' }}
        showSearch
        filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
      >
        {
          db.get("dictTypeList") && db.get("dictTypeList")["course_type"].map((item, index) => {
            if ((courseType == '1') && (item.value == '1' || item.value == '2' || item.value == '4')) {
              return <Select.Option value={item.value} key={index}>{item.label}</Select.Option>
            }
          })
        }
      </Select>
    },
    {
      title: '时长',
      dataIndex: 'courseDuration',
      hideInSearch: true
    },
    {
      title: '排序',
      dataIndex: 'sorting',
      hideInSearch: true
    },
    {
      title: '可预约人数',
      dataIndex: 'maximumAttendance',
      hideInSearch: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <AuthButton auth={[`lesson:detail`]} type="link" onClick={() => goDetail(record)}>详情</AuthButton>
          <AuthDivider auth={['lesson:detail', `lesson:update`]} type="vertical"></AuthDivider>
          <AuthButton auth={[`lesson:update`]} type="link" onClick={() => goToEdit(record, dispatch)}>编辑</AuthButton>
        </>
      ),
    },
  ]);
  // useEffect(() => {
  //   if(courseType=='3'){
  //     dispatch({
  //       type: 'cubeLesson/fetchShopList',
  //       payload:{
  //         userId:db.get("user").userId
  //       }
  //     }).then((result)=>{
  //       columns.push(
  //         {
  //           title: '场馆',
  //           dataIndex: 'venueId',
  //           hideInTable:true,
  //           renderFormItem:()=><Select placeholder="请选择"  style={{width:'100%'}}>
  //              {
  //                 result&&result.map((item,index)=> <Select.Option value={item.id} key={index}>{item.name}</Select.Option>)
  //               }
  //           </Select>
  //         })
  //       setColumns(columns)
  //     })

  //   }
  //  }, []);
  /**
   * 跳转新增页
   * @param {*} record 
   */
  const goToSave = async => {
    history.push(`/lesson/list/save/${props.courseType}`);
  }

  /**
   * 跳转教练详情
   * @param {*} record 
   */
  const go2UserDetail = (record) => {
    history.push(`/employee/list/detail/${record.userId}`);
  }


  /**
   * 跳转编辑页
   * @param {*} record 
   */
  const goToEdit = (record) => {
    history.push(`/lesson/list/update/${record.type}/${record.id}`);
  }
  return (
    <ProTable
      actionRef={actionRef}
      rowKey="id"
      toolBarRender={(action, { selectedRows }) => [
        <AuthButton auth={[`lesson:add`]} type="primary" icon={<PlusOutlined />} onClick={() => goToSave()}>新增</AuthButton>,
        selectedRows && selectedRows.length > 0 && (
          <Dropdown
            overlay={
              <Menu
                onClick={async e => {
                  if (e.key === 'remove') {
                    await handleRemove(selectedRows);
                    action.reload();
                  }
                }}
                selectedKeys={[]}
              >
                <Menu.Item key="remove">批量删除</Menu.Item>
              </Menu>
            }
          >
            <AuthButton auth={[`lesson:batch:delete`]} > 批量操作 <DownOutlined /></AuthButton>
          </Dropdown>
        ),
      ]}
      tableAlertRender={({ selectedRowKeys, selectedRows }) => (
        <div>
          已选择{' '}
          <a
            style={{
              fontWeight: 600,
            }}
          >
            {selectedRowKeys.length}
          </a>{' '}
          项
        </div>
      )}
      request={params => {
        let _params = {
          pageNum: params.current,
          classType: courseType,
          ...params,
        }
        delete _params.current
        return queryLesson(_params)
      }}
      postData={result => {
        setTotal(result.total)
        return result.list
      }}
      pagination={{
        total: total
      }}
      columns={columns}
      rowSelection={{}}
    />
  );
};

export default connect(({ loading, cubeLesson }) => ({
  shopList: cubeLesson.shopList,
  courseList: cubeLesson.courseList,
  coachList: cubeLesson.coachList
}))(List);
